import 'package:aero_frisbee/app/conf/local_resource.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/af_message_detail_screen.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_bottom_input_field_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'input_content/af_input_content_emoji_view.dart';
import 'input_content/af_input_content_file_view.dart';
import 'input_content/af_input_content_record_view.dart';

class AfBottomInputFieldView extends ConsumerStatefulWidget {
  const AfBottomInputFieldView({
    super.key,
    required this.inputField,
    required this.inputText,
    required this.userId,
    required this.textController,
    this.sendOnClick,
  });

  final String inputText;
  final String userId;

  final TextEditingController textController;

  final Function()? sendOnClick;

  final Widget inputField;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfBottomInputFieldViewState();
}

class _AfBottomInputFieldViewState
    extends ConsumerState<AfBottomInputFieldView> {
  @override
  Widget build(BuildContext context) {
    final afBottomInputTypeState = ref.watch(afBottomInputTypeServiceProvider);

    return Column(
      children: [
        afBottomInputTypeState.maybeWhen(
          orElse: () => const SizedBox(
            height: 0,
          ),
          file: () => AfInputContentFileView(
            onSelectedFile: () {
              FilePicker.platform.pickFiles().then((value) {
                if (value != null && value.files.isNotEmpty) {
                  String path = value.files.first.path!;

                  ref
                      .read(afMessageDetailListServiceProvider(
                              userId: widget.userId)
                          .notifier)
                      .sendFileMessage(path);
                }
              });
            },
            onSelectedImg: () async {
              if (!await Permission.photos.isGranted) {
                var permissionStatus = await Permission.photos.request();
                if (permissionStatus != PermissionStatus.granted) {
                  "You have not authorised this permission.".toast();
                  return;
                }
              }
              final ImagePicker picker = ImagePicker();
              picker.pickImage(source: ImageSource.gallery).then((file) {
                if (file != null) {
                  print("image.path 判断file对象不为空 file.path == ${file.path}");
                  ref
                      .read(afMessageDetailListServiceProvider(
                              userId: widget.userId)
                          .notifier)
                      .sendImageMessage(file.path);
                }
              });
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 10),
          child: Row(
            children: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  ref
                      .read(afBottomInputTypeServiceProvider.notifier)
                      .toggleRecord();
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 10, left: 10),
                  child: afBottomInputTypeState.maybeWhen(
                    orElse: () =>
                        Assets.images.chat.chatInputRecord.image(width: 32),
                    record: () => Assets.images.chat.chatInputBarKeyboard.image(
                      width: 32,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: SizedBox(
                  height: 32,
                  child: Stack(
                    children: [
                      widget.inputField,
                      Positioned.fill(
                        child: Visibility(
                          visible: afBottomInputTypeState.maybeWhen(
                            record: () => true,
                            orElse: () => false,
                          ),
                          child: AfInputContentRecordView(
                            onRecorderEnd: (path, duration) {
                              ref
                                  .read(afMessageDetailListServiceProvider(
                                          userId: widget.userId)
                                      .notifier)
                                  .sendVoiceMessage(
                                      path: path!, duration: duration ?? 0);
                            },
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              if (widget.inputText.isNotEmpty)
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    FocusManager.instance.primaryFocus?.unfocus();
                    widget.sendOnClick?.call();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: const Color(0xffDDFB6C),
                      borderRadius: BorderRadius.circular(30),
                    ),
                    padding:
                        const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    margin:
                        const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
                    child: const Center(
                      child: Text(
                        'Send',
                        style: TextStyle(
                          color: Color(0xff404040),
                          fontWeight: FontWeight.normal,
                          fontSize: 16,
                        ),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                  ),
                )
              else
                Row(
                  children: [
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        ref
                            .read(afBottomInputTypeServiceProvider.notifier)
                            .toggleEmoji();
                      },
                      child: Padding(
                        padding: const EdgeInsets.only(right: 10, left: 10),
                        child: afBottomInputTypeState.maybeWhen(
                          orElse: () => Assets.images.chat.chatInputEmoji
                              .image(width: 32),
                          emoji: () =>
                              Assets.images.chat.chatInputBarKeyboard.image(
                            width: 32,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        ref
                            .read(afBottomInputTypeServiceProvider.notifier)
                            .toggleFile();
                      },
                      child: Padding(
                        padding: const EdgeInsets.only(right: 10, left: 10),
                        child: Assets.images.chat.chatInputAddFile.image(
                          width: 32,
                        ),
                      ),
                    )
                  ],
                )
            ],
          ),
        ),
        afBottomInputTypeState.maybeWhen(
          orElse: () => const SizedBox(
            height: 0,
          ),
          emoji: () => AfInputContentEmojiView(
            onEmojiDelete: () {
              final text = widget.textController.text;
              final textSelection = widget.textController.selection;
              final selectionLength = textSelection.end - textSelection.start;

              // There is a selection.
              if (selectionLength > 0) {
                final newText = text.replaceRange(
                  textSelection.start,
                  textSelection.end,
                  '',
                );
                setState(() {
                  widget.textController.text = newText;
                  widget.textController.selection = textSelection.copyWith(
                    baseOffset: textSelection.start,
                    extentOffset: textSelection.start,
                  );
                });
                return;
              }

              // The cursor is at the beginning.
              if (textSelection.start == 0) {
                return;
              }

              // Delete the previous character
              int charSize = 1;
              if (textSelection.start > 1) {
                String sub = text.substring(
                    textSelection.start - 2, textSelection.start);
                if (LocalResource.emojisList.contains(sub)) {
                  charSize = 2;
                }
              }

              int newStart = textSelection.start - charSize;
              int newEnd = textSelection.start;
              final newText = text.replaceRange(
                newStart,
                newEnd,
                '',
              );
              ref.read(inputTextProvider.notifier).state = newText;
              setState(() {
                widget.textController.text = newText;
                widget.textController.selection = textSelection.copyWith(
                  baseOffset: newStart,
                  extentOffset: newStart,
                );
              });
            },
            onEmojiSelected: (value) {
              final text = widget.textController.text;
              final textSelection = widget.textController.selection;
              final newText = text.replaceRange(
                textSelection.start,
                textSelection.end,
                value,
              );
              final myTextLength = value.length;
              ref.read(inputTextProvider.notifier).state = newText;
              setState(() {
                widget.textController.text = newText;
                widget.textController.selection = textSelection.copyWith(
                  baseOffset: textSelection.start + myTextLength,
                  extentOffset: textSelection.start + myTextLength,
                );
              });
            },
          ),
        )
      ],
    );
  }
}
